package com.demo.key.show_admob

import com.demo.key.load_admob.AdmobKeyType
import com.demo.key.load_admob.LoadAdmob0822Manager
import com.demo.key.pa.Abs0822Page
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.appopen.AppOpenAd
import com.google.android.gms.ads.interstitial.InterstitialAd
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ShowFullAd0822(
    private val context:Abs0822Page,
    private val type:String,
    private val showFinish:()->Unit
) {

    fun loadFullAdFinish() = LoadAdmob0822Manager.getAdDataByType(type)?.admob!=null

    fun show(){
        if (LoadAdmob0822Manager.showingFullAd0822||!context.resume0822){
            showFinish.invoke()
            return
        }
        val ad = LoadAdmob0822Manager.getAdDataByType(type)
        if (ad?.admob != null){
            LoadAdmob0822Manager.showingFullAd0822=true
            val adAny = ad.admob
            if (adAny is AppOpenAd){
                adAny.fullScreenContentCallback=callback
                adAny.show(context)
            }
            if (adAny is InterstitialAd){
                adAny.fullScreenContentCallback=callback
                adAny.show(context)
            }
        }
    }

    private val callback=object : FullScreenContentCallback() {
        override fun onAdDismissedFullScreenContent() {
            super.onAdDismissedFullScreenContent()
            LoadAdmob0822Manager.showingFullAd0822=false
            showFullAdFinish()
        }

        override fun onAdShowedFullScreenContent() {
            super.onAdShowedFullScreenContent()
            LoadAdmob0822Manager.showingFullAd0822=true
            LoadAdmob0822Manager.removeAdmobData(type)
        }

        override fun onAdFailedToShowFullScreenContent(p0: AdError) {
            super.onAdFailedToShowFullScreenContent(p0)
            LoadAdmob0822Manager.showingFullAd0822=false
            LoadAdmob0822Manager.removeAdmobData(type)
            showFullAdFinish()
        }
    }

    private fun showFullAdFinish(){
        if (AdmobKeyType.CONNECT==type){
            LoadAdmob0822Manager.logic(type)
        }
        GlobalScope.launch(Dispatchers.Main) {
            delay(200L)
            if (context.resume0822){
                showFinish.invoke()
            }
        }
    }
}